<?php
/**********************************************************
Copyright (c) 2011 Wayne State University Library System
Licensed under the MIT License.
Redistributions of files must retain the above copyright notice.

This software is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

MapIt!
http://www.lib.wayne.edu/MapIt!/
http://code.google.com/XXXX
contact: Paul Gallagher, Developer Librarian WSULS
email: paul.gallagher@wayne.edu
***********************************************************/
require_once('config/config.inc.php');
require_once('MDB2.php');
require_once('../lib/functions.php');

//enable debug options
if ($debug == true) {
	ini_set('display_errors',1);
	error_reporting(E_ALL);	
}

//#####################  Page Logic  #############################
//sanitize the array
$clean = array();
foreach ($_GET as $key => $value) {
	$clean[$key] = mysql_real_escape_string($value);
}

	// create MDB2 instance
	$mdb2 = MDB2::factory($dsn);
	$mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
	$query = "SELECT *, IF(ISNULL(location_subcode), location_code, CONCAT(location_code, location_subcode)) AS location_jointcode FROM locations WHERE IF(ISNULL(location_subcode), location_code, CONCAT(location_code, location_subcode)) = '$clean[location_code]'";
	$result = $mdb2->query($query);
	$array = $result->fetchRow();
	$result->free();
	
	if ($debug == true) {
		print_r($array);
	}

//#####################  Form Submission Logic  #############################
//check for empty submission, prevents processing before form load
if (!empty($_POST) && $_POST["id"] == "call_update")		
	{	
		$clean1 = array();	//sanitize the form
		foreach ($_POST as $key => $value) {
			$clean1[$key] = mysql_real_escape_string($value);
		}
			//setup the calls
			$EndNormal = LCCallToNumber($clean1['end']);
			$StartNormal = LCCallToNumber($clean1['start']);
			$StartCall = $clean1['start'];
			$EndCall = $clean1['end'];
			
			if ($StartNormal > $EndNormal) { //Switch the start and end if reversed
				$EndNormal = LCCallToNumber($clean1['start']);
				$StartNormal = LCCallToNumber($clean1['end']);
				$StartCall = $clean1['end'];
				$EndCall = $clean1['start'];
			}


		if ($clean1["call_range"] == "new") {  //add
				$query = "INSERT INTO locations_calls (location_code, location_subcode, start_call, end_call, width, height, x, y, orig_start_call, orig_end_call) VALUES ('$array[location_code]','$array[location_subcode]', $StartNormal, $EndNormal, $clean1[width], $clean1[height], $clean1[x], $clean1[y], '$StartCall', '$EndCall')";	
		}  
		elseif ($clean1["delete"] == "on") {  //delete
			$query = "DELETE FROM locations_calls WHERE id = $clean1[call_range]";
			unlinkByWildcard('../maps/dynamic/');
		}
		else  {		//update
			 if ($clean1[width] != "" && $clean1[height] != "")	{ 	//update everything
				 $query = "UPDATE locations_calls SET location_code = '$array[location_code]', location_subcode = '$array[location_subcode]', start_call = '$StartNormal', end_call = '$EndNormal', width = $clean1[width], height = $clean1[height], x = $clean1[x], y = $clean1[y], orig_start_call = '$StartCall', orig_end_call = '$EndCall' WHERE id = $clean1[call_range]";
				
			 }
			 else  {												//update only the call number
				 $query = "UPDATE locations_calls SET location_code = '$array[location_code]', location_subcode = '$array[location_subcode]', start_call = '$StartNormal', end_call = '$EndNormal', orig_start_call = '$StartCall', orig_end_call = '$EndCall' WHERE id = $clean1[call_range]";
			 }
				unlinkByWildcard('../maps/dynamic/');
		}
		
			//do the commit		
			 $affected =& $mdb2->exec($query);
			if (PEAR::isError($affected)) {
				die($affected->getMessage());
			}

}

//#####################  Functions #############################
function CreateCallOptionBox($dsn, $location_code)	{
	// create MDB2 instance
	$mdb2 = MDB2::factory($dsn);
	$mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
	$query = "SELECT *, IF(ISNULL(location_subcode), location_code, CONCAT(location_code, location_subcode)) AS location_jointcode FROM locations_calls WHERE IF(ISNULL(location_subcode), location_code, CONCAT(location_code, location_subcode)) = '$location_code' ORDER BY start_call";
	$result = $mdb2->query($query);
	$array = $result->fetchAll();
	$result->free();
	
	if ($debug == true) {
		print_r($array);
	}
	
	//create opt, add the new option
	$opt = '<option value="new">New</option>';
	
	//Create option box value from each subarray
	foreach($array as $subarray)	{
		foreach($subarray as $key => $data)	{
		//Check the id, provide the output tag
			switch($key)	{
				case ($key == 'id'):
					$opt .= '<option value="' . $data . '">';
				break;
			
				case ($key == 'orig_start_call'):
					$opt .= $data.' - ';
				break;

				case ($key == 'orig_end_call'):
					$opt .= $data . '</option>';
				break;
			}
		}
	}
	//print the option box	
	return ('<select name="call_range" id="callRange" onchange="changePage(this, this.selectedIndex)" >' . $opt . '</select>');
}


//#####################  Display Code #############################
ob_start("callback");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WSULS Mapping System Update Form</title>
<script language="JavaScript" type="text/javascript">
function changePage(obj, index)	
	 {
		if (obj.options[index].text != 'New')
		{
			var selected_text = obj.options[index].text;
			var j = selected_text.search('-');
			var callStart = selected_text.substring(0, j);
			var callEnd = selected_text.substring((j+2));
			
			//push option box data into form fields
			document.pointform.start.value = callStart;
			document.pointform.end.value = callEnd;
			
			//show the production version
			var objFrame = document.getElementById("frame"); 
			objFrame.style.visibility = 'visible';
			objFrame.style.width = "100%";
			objFrame.style.height = '1000px';
			objFrame.src = '../index.php?location=<?php print($array['location_code']); ?>&call=' + callStart;
		}
		else
		{
			document.pointform.start.value = '';
			document.pointform.end.value = '';
		}
	 }
</script>
<script language="JavaScript" type="text/javascript" src="js/overlay.js"></script>
</head>
<body>
<?php include('menu.php'); ?>
<br />
<table width="100%" border="0" cellspacing="2" cellpadding="2" bgcolor="#CCCCCC">
  <tr>
    <td colspan="2">
    <form enctype="multipart/form-data" action="<?php echo $PHP_SELF;?>" method="post" id="call_update" name="pointform">
        <table width="603" border="0" cellspacing="2" cellpadding="2">
          <tr>
            <td colspan="8">Range to update:&nbsp;<?php print(CreateCallOptionBox($dsn, $clean['location_code'])); ?>&nbsp;OR
                <input type="checkbox" name="delete" id="delete" />
                <label>
                	&nbsp;delete the range 
                </label>
             </td>
          </tr>
          <tr>
            <td width="23%"><div align="center">Start:</div></td>
            <td width="23%"><div align="center">End</div></td>
            <td width="13%">&nbsp;</td>
            <td width="6%" bgcolor="#CCCCCC"><div align="center">Y</div></td>
            <td width="6%" bgcolor="#CCCCCC"><div align="center">X</div></td>
            <td width="9%" bgcolor="#CCCCCC"><div align="center">Width:</div></td>
            <td width="20%" colspan="2" bgcolor="#CCCCCC"><div align="center">Height:</div></td>
          </tr>
          <tr>
            <td><div align="center">
                <input name="start" id="start" type="text" style="width:120px" />
              </div></td>
            <td><div align="center">
                <input name="end" id="end" type="text" style="width:120px" />
              </div></td>
            <td>&nbsp;</td>
            <td bgcolor="#CCCCCC"><div align="center">
                <input name="y" type="text" style="width:30px" readonly />
              </div></td>
            <td bgcolor="#CCCCCC"><div align="center">
                <input name="x" type="text" style="width:30px" readonly />
              </div></td>
            <td bgcolor="#CCCCCC"><div align="center">
                <input name="width" type="text" style="width:30px" readonly />
              </div></td>
            <td bgcolor="#CCCCCC"><div align="center">
                <input name="height" type="text" style="width:30px" readonly />
              </div></td>
          </tr>
          <tr>
            <td colspan="8">
            <input type="submit" value="Submit" />
              <input type="hidden" name="id" value="call_update" />
              NOTE: Call number ranges MUST <acronym title="If case 1 ends at B45, case 2 MUST start higher than B45, such as B45.A or B46.">NOT OVERLAP</acronym>
              </td>
          </tr>
        </table>
      </form>
      <div id="pointer_div" name="pointer" style="position:absolute;"></div>
      <img id="pointer" name="img_pointer" style="cursor: crosshair;" onClick="point_it(event)"  src="<?php echo('../maps/templates/' . $array['template']) ?>" alt="Please upload a map of <?php echo($array['template']) ?> to continue" />
      </td>
  </tr>
</table>

<iframe id="frame" name="frame" width="0px" height="0px" src="../index.php?location=<?php echo($array['location_code'] . "&call=" . $_POST[end] . "1") ?>" frameborder="0" scrolling="no">
<p>Your browser does not support iframes.</p>
</iframe>

</body>
</html>
<?php ob_end_flush(); ?>
